<template>
  <div class="my-menu">
    <div
      class="menu-item"
      v-for="item of menuList"
      :key="item.name"
      :class="{
        active: currentActive === item.name,
      }"
      @click="updateActive(item)"
    >
      {{ item.title }}
    </div>
  </div>
</template>

<script lang="ts" setup>
import { computed, ref, watchEffect } from "vue";
import { useRouter, type RouteRecordName } from "vue-router";
import { routes } from "@/router/router";
import { userInfo } from "@/utils/userInfo";
import { rolePermissions } from "@/router/config.ts";
import { roleType } from "@/store/useRole";
const router = useRouter();

interface MenuItem {
  title: string;
  name: string;
  path?: string;
}
const menuList = computed((): MenuItem[] => {
  return routes
    .map((route) => {
      return {
        path: route.path,
        title: route?.meta?.title,
        name: route.name,
      } as MenuItem;
    })
    .slice(2)
    .filter((item: MenuItem) => {
      // @ts-ignore
      return rolePermissions[
        userInfo?.value?.role ?? roleType.NotLogin
      ].includes(item.path);
    });
});
const currentActive = ref();
watchEffect(() => {
  currentActive.value = router.currentRoute.value.matched[0]?.name as string;
});
const updateActive = (item: MenuItem) => {
  const routeName = item.name as RouteRecordName;
  currentActive.value = routeName;
  router.push({
    name: routeName,
  });
  document.title = `实验管理平台-${item.title}`;
};
</script>
<style scoped lang="scss">
/* @import url(); 引入css类 */
.my-menu {
  width: 200px;
  position: sticky;
  top: 120px;
  .menu-item {
    padding: 6px 10px;
    margin-bottom: 10px;
    cursor: pointer;
    border-radius: 4px;

    &:hover {
      color: #2a55e5;
    }

    &.active {
      color: #2a55e5;
      background: #f0f1f3;
    }
  }
}
</style>
